<!--视频封面-->
<template>
  <div v-if="url" class="video-cover" ref="imgWrap">
    <video id="video" ref="video" @loadeddata ="onplay" :src="url" preload="auto" ></video>
    <canvas ref="canvas"></canvas>
  </div>
</template>

<script>
  export default {
    props: ['url'],
    name: 'videoCoverComponent',
    data () {
      return {
      }
    },
    mounted () {
    },
    methods: {
      onplay () {
        let video = document.getElementById('video')
//        let video = this.$refs.video
        let canvas = this.$refs.canvas
        let ctx = canvas.getContext('2d')
        let width = video.clientWidth || 1600
        let height = video.clientHeight || 900
        video.volume = 0
        canvas.width = width
        canvas.height = height
        ctx.drawImage(video, 0, 0, width, height)
        this.saveImage(canvas)
      },
      saveImage (canvas) {
        var image = canvas.toDataURL('image/png').replace('image/png', 'image/octet-stream')
        let blob = this.convertBase64UrlToBlob(image)
        let file = new window.File([blob], Date.now()+'.png', {type: blob.type})
        console.log(file)
        this.$emit('onCover', file, image)
      },
      convertBase64UrlToBlob (urlData) {
        let bytes = window.atob(urlData.split(',')[1])        //去掉url的头，并转换为byte
        //处理异常,将ascii码小于0的转换为大于0
        let ab = new ArrayBuffer(bytes.length)
        let ia = new Uint8Array(ab)
        for (let i = 0; i < bytes.length; i++) {
          ia[i] = bytes.charCodeAt(i)
        }

        return new Blob([ab], {type: 'image/png'})
      }
    }
  }
</script>

<style scoped lang="scss">
  .video-cover {
    width: 0; height: 0;
    overflow: hidden;
  }
  video {
    max-width:100vw;
  }
</style>
